import pandas as pd
import re
from typing import Dict, List

from interfaces.transformers import ICycleProcessor


class CycleProcessor(ICycleProcessor):
    def process_cycles(self, all_results: Dict[str, pd.DataFrame], cycle: List[str], sources: List[str]) -> None:
        base_df = all_results.get("入组成功受试者")
        if base_df is None or "受试者编号" not in base_df.columns:
            return

        for current_cycle in cycle:
            cycle_agg_df = base_df[["受试者编号"]].copy()
            cycle_table_name = f"{current_cycle}_访视日期"
            for source in sources:
                source_df = all_results.get(source)
                if source_df is None:
                    continue
                required_cols = ["受试者编号", "数据节", "行号"]
                if any(col not in source_df.columns for col in required_cols):
                    continue
                filtered_df = source_df[(source_df["行号"] == "1") & (source_df["数据节"] == current_cycle)].copy()
                if filtered_df.empty:
                    continue
                xxdat_pattern = re.compile(r'^.{2}DAT$', re.IGNORECASE)
                xxdat_cols = [col for col in filtered_df.columns if xxdat_pattern.match(col)]
                dsstdat_cols = [col for col in filtered_df.columns if col.upper() == "DSSTDAT"]
                target_cols = xxdat_cols + dsstdat_cols
                if not target_cols:
                    continue
                renamed_cols = {col: f"{source}_{col}" for col in target_cols}
                source_target_df = filtered_df[["受试者编号"] + target_cols].rename(columns=renamed_cols)
                cycle_agg_df = pd.merge(cycle_agg_df, source_target_df, on="受试者编号", how="left")
            all_results[cycle_table_name] = cycle_agg_df
